<?php
	use\ampleharvest\code\cConfig;
	require_once dirname(dirname(dirname(__FILE__))) . '/config/cConfig.php';

	require_once dirname(dirname(dirname(__FILE__))) . '/classes/Tables/cTABLE_Data.php';
	require_once dirname(dirname(dirname(__FILE__))) . '/classes/Tables/cTABLE_Data_Ref.php';

	require_once dirname(dirname(dirname(__FILE__))) . '/classes/cAmpleHarvestLog.php';

	require_once dirname(dirname(dirname(__FILE__))) . '/classes/cStomp.php';
	require_once dirname(dirname(dirname(__FILE__))) . '/validation/json/cJsonValidator.php';
	/**
	 * @brief This class Describes the Query_History Table in the AmpleHarvest Database
	 *
	 * - Revision History
	 *  - 0.1
	 * 	 - <b>Date</b>: 02 JUN 2011
	 * 	 - <b>Author</b>: Randy Blancett
	 * 	  - Initial Version
	 *
	 * @author Randy Blancett
	 * @version 0.1
	 * @ingroup code
						
	 */
	set_error_handler('exceptions_error_handler');

	function exceptions_error_handler($severity, $message, $filename, $lineno)
	{
		if (error_reporting() == 0)
		{
			return;
		}
		if (error_reporting() & $severity)
		{
			throw new ErrorException($message, 0, $severity, $filename, $lineno);
		}
	}

	//Number of Data sets to process in one pass.
	$int_GroupSize = 100;

	$arr_DataSets = array();

	$obj_Log = new cAmpleHarvestLog();

	//Setup Stomp
	$obj_StompCon = new cStomp();

	$obj_TABLE_Data = new cTABLE_Data();
	$obj_TABLE_Data_Ref = new cTABLE_Data_Ref();

	//Search for all Rows that have a current status of New
	$obj_TABLE_Data->start_Group();

	$obj_TABLE_Data->add_ColumnQuery($obj_TABLE_Data->m_int_COL_Status, cTABLE_Data::C_INT_STATUS_NEW);

	$obj_TABLE_Data->end_Group();

	$obj_TABLE_Data->start_Group(cQuery::c_str_JOIN_OR);

	$obj_TABLE_Data->add_ColumnQuery($obj_TABLE_Data->m_int_COL_DataToken,
		$obj_TABLE_Data->get_Column_Name($obj_TABLE_Data->m_int_COL_ProcessToken),
		cCondition::c_str_OPERATOR_NOT,
		cQuery::c_str_JOIN_AND,
		cCondition::C_INT_FORMAT_COLUMN);

	$obj_TABLE_Data->add_ColumnQuery($obj_TABLE_Data->m_int_COL_Status,
		cTABLE_Data::C_INT_STATUS_PROCESSING_DATA,
		cCondition::c_str_OPERATOR_GREATER);

	$obj_TABLE_Data->end_Group();

	$obj_TABLE_Data->set_Limit($int_GroupSize);

	//Do Query
	$int_Items = $obj_TABLE_Data->do_Search();
	print("Processing " . $int_Items . " rows of data\n");

	$obj_Log->do_Log(cAmpleHarvestLog::C_STR_ACTION_DATA_PROC_1_INFO,
		"Processing Level 1 Started Processing $int_Items itmes.",
		cAmpleHarvestLog::C_INT_LEVEL_INFO);

	if ($int_Items < 1)
	{
		exit(0);
	}

	$arr_Results = $obj_TABLE_Data->get_ResultSet();

	//print_r($arr_DataSets);
	foreach ($arr_Results as $arr_Result)
	{
		$obj_Temp = new cTABLE_Data();
		$obj_Temp->load_DataFromArray($arr_Result);
		$arr_DataSets[] = clone $obj_Temp;

		$obj_Temp->set_data();

		$obj_Temp->set_status(cTABLE_Data::C_INT_STATUS_PROCESSING_DATA);

		$obj_Temp->save_Data2DB();

	}

	foreach ($arr_DataSets as $obj_DataSet)
	{
		$bool_Save = true;
		$obj_TABLE_Data_Ref->clear();

		$str_Json = cTABLE_Data::decode($obj_DataSet->get_data());

		try
		{
			$arr_Json = json_decode($str_Json);
		}
		catch (Exception $e)
		{
			$obj_DataSet->set_status(cTABLE_Data::C_INT_STATUS_STAGE_1_FAIL);

			if (!$obj_DataSet->save_Data2DB())
			{
				$obj_Log->do_Log(cAmpleHarvestLog::C_STR_ACTION_DATA_PROC_1_ERROR,
					$obj_DataSet->get_id() . " had an error updateing its information in the database.",
					cAmpleHarvestLog::C_INT_LEVEL_ERRORS);
				print("Error Writeing to Database\n");
			}

			$obj_Log->do_Log(cAmpleHarvestLog::C_STR_ACTION_DATA_PROC_1_ERROR,
				$obj_DataSet->get_id() . " the following problem unserializeing " . $e,
				cAmpleHarvestLog::C_INT_LEVEL_ERRORS);
			continue;
		}

		if (validate_Json($arr_Json))
		{
			if (validate_Row($obj_DataSet, $arr_Json))
			{
				if (isset($arr_Json->harvestDate))
				{
					$obj_DataSet->set_harvest_date($arr_Json->harvestDate);
				}
				if (isset($arr_Json->publishDate))
				{
					try
					{
						$obj_DataSet->set_publish_date($arr_Json->publishDate);
					}
					catch (Exception $e)
					{

					}
				}
				if (isset($arr_Json->origId))
				{
					$obj_DataSet->set_orig_id($arr_Json->origId);
				}
				if (isset($arr_Json->source))
				{
					$obj_DataSet->set_source($arr_Json->source);
				}

				if (isset($arr_Json->origId))
				{
					$str_ID = $arr_Json->origId;
					$int_Page = $arr_Json->page;

					if (!is_numeric($int_Page) || $int_Page < 1)
					{
						$int_Page = 1;
					}

					if ($str_ID != "")
					{
						$bool_SetRef = true;

						/*					$obj_TABLE_Data_Ref->clear_Query();
						 $obj_TABLE_Data_Ref->add_ColumnQuery($obj_TABLE_Data_Ref->m_int_COL_OrigID, $str_ID);
						 $obj_TABLE_Data_Ref->add_ColumnQuery($obj_TABLE_Data_Ref->m_int_COL_Page, $int_Page);
						 if ($obj_TABLE_Data_Ref->do_Search() > 0)
						 {
						 $arr_Temp = $obj_TABLE_Data_Ref->get_ResultSet();
																		
						 foreach ($arr_Temp as $arr_Row)
						 {
						 $obj_TABLE_Data_Ref->clear();
						 $obj_TABLE_Data_Ref->load_DataFromArray($arr_Row);
																		
						 if ($obj_DataSet->get_id() != $obj_TABLE_Data_Ref->get_guid())
						 {
						 //print("Orig ID - $str_ID\n");
						 //print("Page - $int_Page\n");
						 //print("Input ID - ".$obj_DataSet->get_id()."\n");
						 //print("ref ID - ".$obj_TABLE_Data_Ref->get_guid()."\n");
						 //die("Killed at ".__LINE__);
						 delete($obj_TABLE_Data_Ref);
						 }
						 else
						 {
						 $bool_SetRef = false;
						 }
						 }
						 }
						 $obj_TABLE_Data_Ref->clear();
						 $obj_TABLE_Data_Ref->clear_Query();
						 */
						$bool_SetRef = true;
						if ($bool_SetRef)
						{
							$obj_TABLE_Data_Ref->set_origID($str_ID);
							$obj_TABLE_Data_Ref->set_page($int_Page);
							$obj_TABLE_Data_Ref->set_guid($obj_DataSet->get_id());
							$bool_Save = $obj_TABLE_Data_Ref->save_Data2DB();
						}
					}
				}

				$obj_DataSet->set_processToken($obj_DataSet->get_dataToken());
				$obj_DataSet->set_status(cTABLE_Data::C_INT_STATUS_STAGE_1_SUCCESS);
				if (!$bool_Save)
				{
					print("Error Outputing Ref Table\n");

					$obj_Log->do_Log(cAmpleHarvestLog::C_STR_ACTION_DATA_PROC_1_ERROR,
						$obj_DataSet->get_id() . " had an error outputing the referance table information.",
						cAmpleHarvestLog::C_INT_LEVEL_ERRORS);

					$obj_DataSet->set_status(cTABLE_Data::C_INT_STATUS_STAGE_1_FAIL);
				}
			}
			else
			{
				$obj_DataSet->set_status(cTABLE_Data::C_INT_STATUS_STAGE_1_FAIL);
			}
		}
		else
		{
			$obj_DataSet->set_status(cTABLE_Data::C_INT_STATUS_STAGE_1_FAIL);
		}

		//		}
		if (!$obj_DataSet->save_Data2DB())
		{
			$obj_Log->do_Log(cAmpleHarvestLog::C_STR_ACTION_DATA_PROC_1_ERROR,
				$obj_DataSet->get_id() . " had an error updateing its information in the database.",
				cAmpleHarvestLog::C_INT_LEVEL_ERRORS);
			print("Error Writeing to Database\n");
		}
		//print_r($arr_Json);

	}

	function validate_Json($obj_Json)
	{
		global $obj_Log, $obj_DataSet;
		$str_SchemaLoc = dirname(dirname(dirname(__FILE__))) . "/validation/json/";
		$str_Schema = file_get_contents($str_SchemaLoc . "AmpleHarvest.json");
		cJsonValidator::add_Path($str_SchemaLoc);

		$int_Return = cJsonValidator::validate($obj_Json, $str_Schema);
		if ($int_Return < 0)
		{
			/*			
			 print($obj_DataSet->get_id() . " had the following error parsing the json " . cJsonValidator::convert_ErrorCode($int_Return) .
			 "\n Schema Location - " . cJsonValidator::get_LastSchemaPos() .
			 "\n Json Location - " . cJsonValidator::get_LastJsonPos() .
			 "\n Error Text - " . cJsonValidator::get_ErrorText());
			 */
			$obj_Log->do_Log(cAmpleHarvestLog::C_STR_ACTION_DATA_PROC_1_ERROR,
				$obj_DataSet->get_id() . " had the following error parsing the json " . cJsonValidator::convert_ErrorCode($int_Return) .
				"\n Schema Location - " . cJsonValidator::get_LastSchemaPos() .
				"\n Json Location - " . cJsonValidator::get_LastJsonPos() .
				"\n Error Text - " . cJsonValidator::get_ErrorText(),
				cAmpleHarvestLog::C_INT_LEVEL_ERRORS);
			return false;
		}
		return true;
	}

	function validate_Row(cTABLE_Data $obj_Data, $obj_Json)
	{
		global $obj_Log;
		if ($obj_Data->get_id() != $obj_Json->id)
		{
			$obj_Log->do_Log(cAmpleHarvestLog::C_STR_ACTION_DATA_PROC_1_ERROR,
				$obj_Data->get_id() . " has miss matching IDs the row id and the Json ID must match",
				cAmpleHarvestLog::C_INT_LEVEL_ERRORS);
			return false;
		}
		return true;
	}

	function delete(cTABLE_Data_Ref $obj_Data)
	{
		global $obj_StompCon;
		$obj_TABLE_Data = new cTABLE_Data();

		$obj_TABLE_Data->add_ColumnQuery($obj_TABLE_Data->m_int_COL_ID, $obj_Data->get_guid());

		print("deleteing " . $obj_Data->get_guid() . "\n");

		if ($obj_TABLE_Data->do_Delete() > 0)
		{
			$arr_Data = $obj_Data->output_AsArray();

			$obj_Data->clear_Query();
			$obj_Data->add_ColumnQuery($obj_Data->m_int_COL_ID, $obj_Data->get_id());
			$obj_Data->do_Delete();

			$obj_StompCon->send(cStomp::C_STR_QUEUE_SOLR_DELETE, json_encode($arr_Data));
		}
		else
		{
			print("Error Deleteing Original Infomration.");
		}
	}
	exit(1);
?>